package me.humin.nio.server;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * @author humin
 * @create 2018-7-2
 */
public class NioServer {

    private static final int port = 35801;

    private final static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public static void main(String[] args) throws Exception {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        ServerSocket ss = ssc.socket();
        ss.bind(new InetSocketAddress(port));

        while (true) {
            int channels = selector.selectNow();
            if (channels > 0) {
                Set<SelectionKey> readyKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = readyKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel sc = (SocketChannel) channel.accept().configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE).attach("client");
                    }
                    if (key.isWritable()) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        String content = "to "  + key.attachment() + " " + format.format(new Date()) + "\n";
                        byte[] bytes = content.getBytes();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
                        byteBuffer.put(content.getBytes());
                        byteBuffer.flip();
                        sc.write(byteBuffer);
                        System.out.println();
                    }
                    if (key.isReadable()) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
                        sc.read(byteBuffer);
                        System.out.println(key.attachment() + ": " + getString(byteBuffer));
                    }
                }
            }
            Thread.sleep(1000);
        }
    }

    public static String getString(ByteBuffer buffer) {
        String string = "";
        try {
            for (int i = 0; i < buffer.position(); i++) {
                string += (char) buffer.get(i);
            }
            return string;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

}
